package com.space9.search.service.impl;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.space9.search.dao.SearchDao;
import com.space9.search.pojo.SearchResult;
import com.space9.search.service.SearchService;

@Service
public class SearchServiceImpl implements SearchService {

	@Autowired
	private SearchDao searchDao;
	@Override
	public SearchResult search(String queryString, int page, int rows) throws Exception {
		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
		System.out.println(queryString);
		MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("item_title", queryString);
		searchSourceBuilder.from((page - 1) * rows);
		searchSourceBuilder.size(rows);
		searchSourceBuilder.query(matchQueryBuilder); 
		
		
		HighlightBuilder highlightBuilder = new HighlightBuilder(); 
		HighlightBuilder.Field highlightTitle = new HighlightBuilder.Field("item_title"); 
		highlightTitle.highlighterType("unified");  
		highlightBuilder.field(highlightTitle); 
		searchSourceBuilder.highlighter(highlightBuilder);
		
		
		SearchRequest searchRequest = new SearchRequest();
		searchRequest.source(searchSourceBuilder);
		//执行查询
		SearchResult searchResult = searchDao.search(searchRequest);
		//计算查询结果总页数
		long recordCount = searchResult.getRecordCount();
		long pageCount = recordCount / rows;
		if (recordCount % rows > 0) {
			pageCount++;
		}
		searchResult.setPageCount(pageCount);
		searchResult.setCurPage(page);
		
		return searchResult;
	}

}
